<template>
  <div class="app-container">
    <div class="module-title">
      <svg-icon icon-class="money" style="font-size:28px;margin-right:8px;"/>
      <span>新增应收款月份报</span>
      <span class="module-desc">添加新的应收款月份报记录</span>
    </div>

    <div class="module-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="poring-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月份" prop="month">
              <el-date-picker
                v-model="form.month"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="form.customerName"
                placeholder="请输入客户名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select
                v-model="form.paymentMethod"
                placeholder="请选择付款方式"
                style="width: 100%"
                clearable
              >
                <el-option label="现金" value="现金" />
                <el-option label="银行转账" value="银行转账" />
                <el-option label="支票" value="支票" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月结天数" prop="monthlySettlementDays">
              <el-input-number
                v-model="form.monthlySettlementDays"
                :min="0"
                :max="365"
                placeholder="请输入月结天数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对账截止日" prop="reconciliationDeadline">
              <el-date-picker
                v-model="form.reconciliationDeadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择对账截止日"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易币种" prop="transactionCurrency">
              <el-select
                v-model="form.transactionCurrency"
                placeholder="请选择币种"
                style="width: 100%"
                clearable
              >
                <el-option label="人民币" value="CNY" />
                <el-option label="美元" value="USD" />
                <el-option label="欧元" value="EUR" />
                <el-option label="日元" value="JPY" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="应收金额" prop="receivableAmount">
              <el-input-number
                v-model="form.receivableAmount"
                :min="0"
                :precision="2"
                placeholder="请输入应收金额"
                style="width: 100%"
                @change="calculateOutstanding"
              >
                <template slot="prepend">¥</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已收金额" prop="receivedAmount">
              <el-input-number
                v-model="form.receivedAmount"
                :min="0"
                :precision="2"
                placeholder="请输入已收金额"
                style="width: 100%"
                @change="calculateOutstanding"
              >
                <template slot="prepend">¥</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="尚欠款金额" prop="outstandingAmount">
              <el-input
                v-model="form.outstandingAmount"
                placeholder="自动计算"
                disabled
                class="outstanding-input"
              >
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              <i class="el-icon-check"></i> 保存
            </el-button>
            <el-button @click="cancel">
              <i class="el-icon-close"></i> 取消
            </el-button>
            <el-button @click="resetForm">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { addPoring } from "@/api/poring/poring"

export default {
  name: "PoringAdd",
  data() {
    return {
      // 提交加载状态
      submitLoading: false,
      // 表单参数
      form: {
        month: null,
        customerName: null,
        paymentMethod: null,
        monthlySettlementDays: 30,
        reconciliationDeadline: null,
        transactionCurrency: 'CNY',
        receivableAmount: 0,
        receivedAmount: 0,
        outstandingAmount: 0,
        remark: null
      },
      // 表单校验
      rules: {
        month: [
          { required: true, message: "月份不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: "客户名称长度在 2 到 100 个字符", trigger: "blur" }
        ],
        paymentMethod: [
          { required: true, message: "付款方式不能为空", trigger: "change" }
        ],
        monthlySettlementDays: [
          { required: true, message: "月结天数不能为空", trigger: "blur" },
          { type: 'number', min: 0, max: 365, message: "月结天数必须在0-365之间", trigger: "blur" }
        ],
        reconciliationDeadline: [
          { required: true, message: "对账截止日不能为空", trigger: "blur" }
        ],
        transactionCurrency: [
          { required: true, message: "交易币种不能为空", trigger: "change" }
        ],
        receivableAmount: [
          { required: true, message: "应收金额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "应收金额必须大于等于0", trigger: "blur" }
        ],
        receivedAmount: [
          { required: true, message: "已收金额不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "已收金额必须大于等于0", trigger: "blur" }
        ],
        remark: [
          { max: 500, message: "备注长度不能超过 500 个字符", trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    /** 计算尚欠款金额 */
    calculateOutstanding() {
      const receivable = parseFloat(this.form.receivableAmount) || 0
      const received = parseFloat(this.form.receivedAmount) || 0
      this.form.outstandingAmount = Math.max(0, receivable - received).toFixed(2)
    },

    /** 验证已收金额 */
    validateReceivedAmount() {
      const receivable = parseFloat(this.form.receivableAmount) || 0
      const received = parseFloat(this.form.receivedAmount) || 0

      if (received > receivable) {
        this.$message.warning('已收金额不能超过应收金额')
        this.form.receivedAmount = receivable
        this.calculateOutstanding()
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证已收金额不能超过应收金额
          const receivable = parseFloat(this.form.receivableAmount) || 0
          const received = parseFloat(this.form.receivedAmount) || 0

          if (received > receivable) {
            this.$message.error("已收金额不能超过应收金额")
            return
          }

          this.submitLoading = true
          addPoring(this.form).then(response => {
            this.$modal.msgSuccess("新增成功")
            this.$emit('refreshData')
            this.submitLoading = false
            this.$router.back()
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },

    /** 取消按钮 */
    cancel() {
      this.$router.back()
    },

    /** 重置表单 */
    resetForm() {
      this.$refs["form"].resetFields()
      this.form = {
        month: null,
        customerName: null,
        paymentMethod: null,
        monthlySettlementDays: 30,
        reconciliationDeadline: null,
        transactionCurrency: 'CNY',
        receivableAmount: 0,
        receivedAmount: 0,
        outstandingAmount: 0,
        remark: null
      }
      this.calculateOutstanding()
    }
  },

  mounted() {
    this.calculateOutstanding()
  },

  watch: {
    'form.receivedAmount': function() {
      this.validateReceivedAmount()
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/module-card.scss";

.module-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  font-weight: 700;
  color: #2980b9;
  margin-bottom: 18px;

  .module-desc {
    font-size: 14px;
    color: #888;
    font-weight: 400;
    margin-left: 18px;
  }
}

.poring-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;

  .el-form-item {
    margin-bottom: 24px;
  }

  .el-input-number {
    width: 100%;
  }

  .outstanding-input {
    .el-input__inner {
      background-color: #f5f7fa;
      color: #e74c3c;
      font-weight: 700;
      font-size: 16px;
    }
  }

  .form-actions {
    text-align: center;
    margin-top: 40px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;

    .el-button {
      margin: 0 10px;
      padding: 12px 24px;
      font-size: 14px;

      i {
        margin-right: 5px;
      }
    }
  }
}

.el-input-group__prepend {
  background: #f0f4fa;
  color: #2980b9;
  font-weight: 600;
  border-color: #dbeafe;
}

.el-textarea__inner {
  border-color: #dbeafe;

  &:focus {
    border-color: #2980b9;
  }
}

.el-input-number {
  .el-input__inner {
    text-align: left;
  }
}

.el-select {
  width: 100%;
}
</style>
